/*

The MIT License

Copyright (c) 2007 Clever Thinking (PrimetexT Ltd)

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
 */

package couk.cleverthinking.javamoney;

import java.math.BigDecimal;
import java.math.MathContext;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Calendar;
import java.util.HashMap;

/**
 * Maintains a map of exchange rates keyed by ISO 4217 currency code. The rate that is stored is the rate to convert from base currency to
 * foreign currency.
 * 
 * Eg. assuming the base currency is GBP, the value returned for USD would be 2.07, ie. 1 GBP = 2.07 USD
 * 
 * @author winz
 * 
 */
public class ExchangeRates {

	private static int dateOfLastLookup = -1; // the date of the last lookup. Used to trigger a daily refresh
	private static HashMap<String, BigDecimal> map;

	private static Connection dbConn = null;

	public static HashMap<String, BigDecimal> getMap() {
		return map;
	}

	/**
	 * Set the database connection that will be used to lookup exchange rates. If not set, ExchangeRates will assume that its map has been
	 * populated externally, or use default dummy values
	 * 
	 * @param dbConn
	 */
	public static void setDbConn(Connection _dbConn) {
		dbConn = _dbConn;
	}

	/**
	 * Sets the SQL select command to retrieve exchange rates. The SQL should return two columns:- 1. The 3 character ISO code 2. A numeric
	 * exchange rate
	 * 
	 * eg. select curr_symbol, cur_rate from g_exchange rate
	 * 
	 * @param sql
	 */
	public static void setSql(String _sql) {
		sql = _sql;
	}

	private static String sql = "select curr_symbol, curr_rate from g_currency";

	/**
	 * Resfreshes the exchange rate map. This could be done in many ways - eg WebService, scraping a website, looking in a database.
	 * 
	 * For now it's populated with dummy values for testing
	 * @throws SQLException 
	 */
	public static void refreshMap() throws SQLException {
		MathContext mc = MathContext.DECIMAL128;
		map = new HashMap<String, BigDecimal>();
		if (dbConn == null) {
			map.put("GBP", makeBigDecimal("1"));
			map.put("PHP", makeBigDecimal("86"));
			map.put("USD", makeBigDecimal("2.05"));
			map.put("EUR", makeBigDecimal("1.3"));
			return;
		}
		PreparedStatement ps = dbConn.prepareStatement(sql);
		ResultSet rs= ps.executeQuery();
		while (rs.next()) {
			map.put(rs.getString(1).trim(),rs.getBigDecimal(2));
		}
		System.out.println("exchange rate map="+map.toString());
	}

	private static BigDecimal makeBigDecimal(String s) {
		BigDecimal bd = null;
		bd = new BigDecimal(s);
		bd.setScale(10);
		return bd;
	}

	/**
	 * Looks up an exchange rate using the ISO code. If this is the first lookup of the day, the map is first refreshed
	 * 
	 * @param iso4217
	 *            code to lookup
	 * @return
	 * @throws SQLException 
	 */
	public static BigDecimal getRate(String iso4217) throws SQLException {
		int i = Calendar.getInstance().get(Calendar.DAY_OF_YEAR);
		if (i != dateOfLastLookup) {
			refreshMap();
			dateOfLastLookup = i;
		}
		return map.get(iso4217.toUpperCase());
	}
}
